<?php
// +----------------------------------------------------------------------
// | Name: 咪乐多管理系统 [ 为了快速搭建软件应用而生的，希望能够帮助到大家提高开发效率。 ]
// +----------------------------------------------------------------------
// | Copyright: (c) 2020~2021 https://www.lvacms.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed: 这是一个自由软件，允许对程序代码进行修改，但希望您留下原有的注释。
// +----------------------------------------------------------------------
// | Author: 西安咪乐多软件 <997786358@qq.com>
// +----------------------------------------------------------------------
// | Version: V1
// +----------------------------------------------------------------------

/**
 * @Name 标签管理服务
 * @Description
 * @Auther 西安咪乐多软件
 * @Date 2021/11/20 19:06
 */

namespace Modules\BlogAdmin\Services\Article;

use Illuminate\Support\Facades\DB;
use Modules\BlogAdmin\Models\BlogArticle;
use Modules\BlogAdmin\Models\BlogArticleLabel;
use Modules\BlogAdmin\Models\BlogArticleType;
use Modules\BlogAdmin\Models\BlogLabel;
use Modules\BlogAdmin\Services\ArticleType\ArticleTypeServices;
use Modules\BlogAdmin\Services\BaseApiServices;
use Modules\Common\Exceptions\MessageData;

class ArticleServices extends BaseApiServices
{
    public function index(array $data){
        $model = BlogArticle::query();
        $model = $this->setWhereQueryProject($model);
        $model = $this->queryCondition($model,$data,"name");
        if (isset($data['article_type_id']) && $data['article_type_id'] != '' && $data['article_type_id'] > 0){
            $model = $model->where('article_type_id',$data['article_type_id']);
        }
        if(isset($data['sort'])){
            $model = $this->querySort($model,$data['sort']);
        }
        $list = $model->with([
                'imageTo'=>function($query){
                    $query->select('id','url','open');
                },
                'articleTo'=>function($query){
                    $query->select('id','name','open_type','attribute');
                },
                'labelTo'
            ])->orderBy('id','desc')
            ->paginate($data['limit'])->toArray();
        return $this->apiSuccess('',[
            'list'=>$list['data'],
            'total'=>$list['total']
        ]);
    }


    public function add(array $data){
        $data = $this->getCommonId($data);
        if($data['content']){
            $data['content'] = $this->setPicUrl($data['content']);
        }
        DB::beginTransaction();
        try{
            $data['created_at'] = date('Y-m-d H:i:s');
            $labelArr = [];
            if(count($data['labelArr'])>0){
                $labelArr = $data['labelArr'];
            }
            unset($data['labelArr']);
            $id = BlogArticle::query()->insertGetId($data);
            $this->addSetLabelArr($data,$labelArr,$id);
            DB::commit();
        }catch(\Exception $e){
            DB::rollBack();
            $this->apiError('添加失败！');
        }
        return $this->apiSuccess('添加成功！');
    }
    private function addSetLabelArr(array $data,array $labelArr,int $id){
        $date = date('Y-m-d H:i:s');
        foreach($labelArr as $k=>$v){
            $label_id = BlogLabel::query()->where('name',$v)->value('id');
            if(!$label_id){
                $label_id =  BlogLabel::insertGetId([
                    'project_id'=>$data['project_id'],
                    'admin_id'=>$data['admin_id'],
                    'name'=>$v,
                    'sort'=>1,
                    'status'=>1,
                    'created_at'=>$date
                ]);
            }
            BlogArticleLabel::insert([
                'article_id'=>$id,
                'label_id'=>$label_id,
                'project_id'=>$data['project_id'],
                'admin_id'=>$data['admin_id']
            ]);
        }
    }
    public function edit(int $id){
        $data = BlogArticle::query()->with([
            'imageTo'=>function($query){
                $query->select('id','url','open');
            },
            'labelTo'
        ])->find($id)?:$this->apiError(MessageData::GET_API_ERROR);
        $data = $data->toArray();
        if($data['content']){
            $data['content'] = $this->getReplacePicUrl($data['content']);
        }
        if($data['label_to']){
            $data['labelArr'] = array_column($data['label_to'],'name');
        }else{
            $data['labelArr'] = [];
        }
        $data['type_arr'] = (new ArticleTypeServices())->getIdArr($data['article_type_id']);
        return $this->apiSuccess(MessageData::GET_API_SUCCESS,$data);
    }

    public function update(int $id,array $data){
        if(isset($data['content']) && $data['content']){
            $data['content'] = $this->setPicUrl($data['content']);
        }
        $data = $this->getCommonId($data);
        DB::beginTransaction();
        try{
            $labelArr = [];
            if(count($data['labelArr'])>0){
                $labelArr = $data['labelArr'];
            }
            unset($data['labelArr']);
            $data['updated_at'] = date('Y-m-d H:i:s');
            BlogArticle::query()->where('id',$id)->update($data);
            $this->editSetLabelArr($data,$labelArr,$id);
            DB::commit();
        }catch(\Exception $e){
            DB::rollBack();
            $this->apiError('修改失败！');
        }
        return $this->apiSuccess('修改成功！');
    }
    private function editSetLabelArr(array $data,array $labelArr,int $id){
        $date = date('Y-m-d H:i:s');
        $labelIdArr = BlogArticleLabel::query()->where('article_id',$id)->pluck('label_id');
        BlogArticleLabel::query()->where('article_id',$id)->delete();
        BlogLabel::query()->whereIn('id',$labelIdArr)->delete();
        foreach($labelArr as $k=>$v){
            $label_id = BlogLabel::query()->where('name',$v)->value('id');
            if(!$label_id){
                $label_id =  BlogLabel::query()->insertGetId([
                    'project_id'=>$data['project_id'],
                    'admin_id'=>$data['admin_id'],
                    'name'=>$v,
                    'created_at'=>$date
                ]);
            }
            BlogArticleLabel::query()->insert([
                'article_id'=>$id,
                'label_id'=>$label_id,
                'project_id'=>$data['project_id'],
                'admin_id'=>$data['admin_id']
            ]);
        }
    }




    public function status(int $id,array $data){
        return $this->commonStatusUpdate(BlogArticle::query(),$id,$data);
    }
    public function sorts(int $id,array $data){
        return $this->commonSortsUpdate(BlogArticle::query(),$id,$data);
    }
    public function del(int $id){
        return $this->commonDestroy(BlogArticle::query(),['id'=>$id]);
    }
    public function delAll(array $idArr){
        return $this->commonDestroy(BlogArticle::query(),$idArr);
    }
    
    public function getLabelList($name){
        $list = [];
        if($name){
            $list = BlogLabel::query()->where('name','like',$name.'%')->pluck('name')->toArray();
        }
        return $this->apiSuccess('',$list);
    }
}
